import { readBody, defineEventHandler } from 'h3'
import { randomUUID } from 'crypto'
import redis from '../../util/redis'

export default defineEventHandler(async (event) => {
  try {
    const body = await readBody(event)
    const name = (body && (body as any).name) || '匿名'
    const score = Number((body && (body as any).score) ?? NaN)

    if (isNaN(score) || score < 0 || score > 50) {
      event.node.res.statusCode = 400
      return { status: 400, message: 'invalid score' }
    }

    const id = typeof randomUUID === 'function' ? randomUUID() : (Date.now().toString(36) + Math.random().toString(36).slice(2))

    const key = 'archery:leaderboard'
    const member = JSON.stringify({ id, name, ts: Date.now(), score })

    // zadd with score = total score; higher is better
    await (redis as any).zadd(key, score, member)
    // keep leaderboard for 7 days from last write
    await (redis as any).expire(key, 7 * 24 * 3600)

    // get descending rank (highest score first)
    const rank = await (redis as any).zrevrank(key, member)
    return { status: 'ok', rank: rank != null ? rank + 1 : null }
  } catch (err: any) {
    event.node.res.statusCode = 500
    return { status: 500, error: String(err) }
  }
})
